package com.vtuzx.kingdee.xqc_core.utils;

import com.vtuzx.kingdee.xqc_core.dao.SyncTaskHistoryDao;
import com.vtuzx.kingdee.xqc_core.dao.SyncTaskDao;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Component
public class SyncDataMigrationUtil {
    private final SyncTaskDao syncTaskDao;
    private final SyncTaskHistoryDao syncTaskHistoryDao;

    public SyncDataMigrationUtil(SyncTaskDao syncTaskDao,
                                 SyncTaskHistoryDao syncTaskHistoryDao) {
        this.syncTaskDao = syncTaskDao;
        this.syncTaskHistoryDao = syncTaskHistoryDao;
    }

    @Scheduled(cron = "0 0 4 * * ?") // 每天凌晨4点执行
    public void migrateOldData() {
        // 计算两天前的00:00:00时间点
        LocalDateTime twoDaysAgo = LocalDateTime.now()
                .minusDays(2)
                .withHour(0).withMinute(0).withSecond(0);
        Date cutoffDate = Date.from(twoDaysAgo.atZone(ZoneId.systemDefault()).toInstant());
        // 构建查询条件
        Criteria criteria = Criteria.where("orderTime").lt(cutoffDate);
        Document sort = new Document("orderTime", 1); // 按时间升序排序
        // 分页处理（每批1000条）
        int pageSize = 1000;
        int pageIndex = 0;
        List<Document> batchToMove;
        do {
            // 分页查询
            Iterator<Document> iterator = syncTaskDao.findList(
                    null, // 使用默认集合名（已在构造函数指定）
                    criteria,
                    sort,
                    null, // 无字段投影
                    pageIndex,
                    pageSize
            );
            batchToMove = new ArrayList<>();
            while (iterator.hasNext()) {
                batchToMove.add(iterator.next());
            }
            if (!batchToMove.isEmpty()) {
                // 批量插入历史表
                syncTaskHistoryDao.insertMany(
                        null, // 使用默认集合名
                        batchToMove,
                        null  // 无事务会话
                );
                // 从最新表批量删除
                for (Document doc : batchToMove) {
                    syncTaskDao.deleteOne(
                            null,
                            Criteria.where("_id").is(doc.getObjectId("_id")),
                            null
                    );
                }
            }
            pageIndex++;
        } while (!batchToMove.isEmpty());
    }
}